﻿using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
using AsyncLibrary.StatusListener;

namespace AsyncLibrary.UI
{
  public partial class LoadingControl : UserControl, ILoadingListener
  {
    private AsyncOperation _op;
    private readonly VirtualThread _thread;
    private readonly SynchronizationContext _syncContext;

    public event Action Loaded;

    public LoadingControl()
    {
      InitializeComponent();
      _thread = new VirtualThread(Name + " Loading Thread");
      components = new Container();
      components.Add(_thread);
      _syncContext = SynchronizationContext.Current;
    }

    public void Init(Control control, AsyncOperation op)
    {
      _op = op;
      control.Dock = DockStyle.Fill;
      Controls.Add(control);
      loadingCircle.ShowPercentage = true;
      loadingCircle.Visible = false;
    }

    public void LoadData()
    {
      _thread.QueueOperation(_op);
    }

    public bool IsLoaded { get; private set; }

    private void RaiseLoaded()
    {
      var handler = Loaded;
      if (handler != null) handler();
    }

    private void StartedCallback(object state)
    {
      loadingCircle.Visible = true;
      loadingCircle.Active = true;
    }

    private void FinishedCallback(object errorMessage)
    {
      loadingCircle.Active = false;
      loadingCircle.Visible = false;
      if (string.IsNullOrEmpty((string) errorMessage))
      {
        IsLoaded = true;
        RaiseLoaded();
      }
      _op.LoadingListener = null;
    }

    public void LoadingStarted()
    {
      _syncContext.Post(StartedCallback, null);
    }

    public void LoadingFinished(string errorMessage)
    {
      _syncContext.Post(FinishedCallback, errorMessage);
    }

    public void FatalError(Exception ex)
    {
    }
  }


}
